﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using GameSchool.Models;
using GameSchool.ViewModels;
using System.Web.Security;
using System.Web.Profile;
using System.Diagnostics;


namespace GameSchool.Controllers
{
    public class GameController : Controller
    {
        GameRepository repository = new GameRepository();
		GameRegistrationRepository gameReg = new GameRegistrationRepository();
		/*
		public GameController(GameRepository rep)
		{ 
			repository = rep;
		}
		*/

        public ActionResult Index()
        {
            return View();
        }

		public ActionResult Test(GameRepository test)
		{
			return View();
		}


		
        public ActionResult games(int? id)
        {
			var UserId = new Guid(Membership.GetUser(HttpContext.User.Identity.Name).ProviderUserKey.ToString());
			if (User.IsInRole("Admin"))
			{
				var items = from n in repository.Games()
							orderby n.ID
							select n;
				return View(items);
			}
			else if (User.IsInRole("Teacher"))
			{
				var items = from n in repository.Games()
							where n.TeacherID == UserId
							orderby n.ID
							select n;
				return View(items);
			}
			else
			{
				return RedirectToAction("UserGames","Game");
			}
        }

		public ActionResult userGames()
		{
			var UserId = new Guid(Membership.GetUser(HttpContext.User.Identity.Name).ProviderUserKey.ToString());

			//Þvílíkt helvítis pickles var þetta....
			//Þetta kallar bara upp þá leiki sem notandi er skráður í
			var items = from p in gameReg.GameRegistrations().Where(p => p.UserID.Equals(UserId))
						join c in repository.Games().Where(c=> c.ID.Equals(c.ID)) on p.GameID equals c.ID
						select c;

			return View(items);
		}


        /* Aðeins umsjónarmaður
         * Þessi fall sækir umbeðin leik svo hægt sé að breyta honum
         * 
         * Todo: láta birta aðeins leiki sem innskráður notandi tengist
         */

        [HttpGet]
        [Authorize(Roles = "Admin")]
        public ActionResult editGame(int? id)
        {
            //has.value ? villutékk vantar hjá mér
            //IEnumerable<Game> item = from n in repository.Games()
            var item = (from n in repository.Games()
                        where n.ID == id.Value
                        select n).SingleOrDefault();

            if (item != null)
            {
                return View(item);
            }
            else
            {
                return RedirectToAction("Index");
            }
        }


        /* Aðeins umsjónarmaður
         * Þessi fall breytir leiknum og vistar í gagnagrunn
         * 
         * 
         */

        [HttpPost]
        [Authorize(Roles = "Admin")]
        public ActionResult editGame(int? id, FormCollection formData)
        {
            //has.value ? villutékk vantar hjá mér
            //IEnumerable<Game> item = from n in repository.Games()
            var item = (from n in repository.Games()
                        where n.ID == id.Value
                        select n).SingleOrDefault();

            if (item != null)
            {
                //Geri breytingar
                UpdateModel(item);


                //Vista breytingar
                repository.Save();
                return RedirectToAction("Games");
            }
            else
            {
                return View();
            }
        }


        /* Aðeins umsjónarmaður
         * Hér fyrir neðan eru 2 controllerar.
         * Þeir sjá um að birta formið "GameForm.cshtml"
         */

        [HttpGet]
        [Authorize(Roles = "Admin")]
        public ActionResult createGame()
        {
            return View(new Game());
        }


        [HttpPost]
        [Authorize(Roles = "Admin")]
        public ActionResult createGame(FormCollection formData)
        {
            Game newGame = new Game();
            repository.Add(newGame);
            UpdateModel(newGame);
            //setja inn validation
            repository.Save();
            return RedirectToAction("Games");
        }


		//Hér er hnoðað saman einu Viewmodeli þar sem mörgum mismunandi upplýsingum er troðið inn í viewið "ViewGame"
		[HttpGet]
        public ActionResult viewGame(int? id)
        {
			//Tilkynningar
			AnnouncementRepository a = new AnnouncementRepository();

			//Borð
			LevelRepository l = new LevelRepository();

			//Leikjaskráningar
			GameRegistrationRepository gRep = new GameRegistrationRepository();

			//Verkefni
			AssignmentRepository assRep = new AssignmentRepository();

			//Prófílar byrja
			ProfileRepository pRep = new ProfileRepository();

			//Stig nemenda
			UserPointsRepository pointsRep = new UserPointsRepository();
						
			var allRegsInGame = from n in gRep.GameRegistrations()
								where n.GameID.Equals(id)
								select n;

			IEnumerable<aspnet_Profile> profiles =		from n in pRep.profiles()
														join r in allRegsInGame on n.UserId equals r.UserID
														select n;

			var AllUserProfilesInGame = from n in allRegsInGame
										select n;
			//Prófílar enda

			//Myndbönd
			VideoRepository vRep = new VideoRepository();

			// UserId innskráðs notanda
			var UserId = new Guid(Membership.GetUser(HttpContext.User.Identity.Name).ProviderUserKey.ToString());

			//Búið til tilvik af Viewmodeli fyrir ViewGame viewið.
			var model = new ViewGameViewModel
			{
				//Skilar upplýsingum um þann leik sem um ræðir
				Game = (from n in repository.Games()
						where n.ID == id.Value
						select n).SingleOrDefault(),

				//Skilar öllum tilkynningum sem eiga að vera við þennan leik
				Announcements = from n in a.Announcements()
								where n.GameID==id
								select n,
				//Skilar öllum borðum sem tilheyra viðkomandi leik
				Levels = from n in l.Levels()
						 where n.GameID==id
						 select n,
				//Skilar öllum verkefnum sem tilheyra leiknum
				Assignments = from n in assRep.Assignments()
							  where n.GameID == id.Value
							  select n,

				//Skilar öllum prófílum sem tilheyra leiknum
				Students = profiles,

				//Skilar stigum þess notanda sem er innskráður
				myPoints = (from n in pointsRep.UserPoints()
						   where n.UserId == UserId
						   select n).SingleOrDefault(),


				allUserPoints = (from n in pointsRep.UserPoints()
								 orderby n.TotalPoints descending
								 select n),

				//Skilar öllum myndböndum sem tilheyra leiknum
				Videos = from n in vRep.Videos()
						 where n.GameID==id.Value
						 select n
			};
				
			return View(model);
        }
    }
}